/**
 * 认证调试工具
 * 用于调试和监控认证相关的问题
 */

// 调试模式开关
export const AUTH_DEBUG = true;

/**
 * 认证调试日志
 */
export function authLog(message: string, data?: any) {
  if (AUTH_DEBUG) {
    console.log(`[AUTH DEBUG] ${message}`, data || '');
  }
}

/**
 * 监控认证状态
 */
export function monitorAuthStatus() {
  if (!AUTH_DEBUG) return;
  
  authLog('Auth status monitoring enabled');
  
  // 监控 localStorage 中的 token 变化
  const originalSetItem = localStorage.setItem;
  localStorage.setItem = function(key: string, value: string) {
    if (key.includes('token') || key.includes('auth') || key.includes('user')) {
      authLog(`LocalStorage SET: ${key}`, value ? `${value.substring(0, 50)}...` : 'null');
    }
    return originalSetItem.call(this, key, value);
  };
  
  // 监控 localStorage 删除
  const originalRemoveItem = localStorage.removeItem;
  localStorage.removeItem = function(key: string) {
    if (key.includes('token') || key.includes('auth') || key.includes('user')) {
      authLog(`LocalStorage REMOVE: ${key}`);
    }
    return originalRemoveItem.call(this, key);
  };
  
  // 监控请求拦截
  const originalFetch = window.fetch;
  window.fetch = async function(...args) {
    const [url] = args;
    if (typeof url === 'string') {
      if (url.includes('/auth/') || url.includes('/logout') || url.includes('/user/info')) {
        authLog(`API Request: ${url}`);
      }
    }
    return originalFetch.apply(this, args);
  };
  
  // 启用路由守卫监控
  monitorRouteGuard();
}

/**
 * 检查认证状态
 */
export function checkAuthStatus() {
  const token = localStorage.getItem('access-token') || 
                localStorage.getItem('accessToken') ||
                sessionStorage.getItem('access-token') ||
                sessionStorage.getItem('accessToken');
  
  // 检查用户信息
  const userInfoStr = localStorage.getItem('vben-user-info') || 
                      sessionStorage.getItem('vben-user-info');
  let userInfo = null;
  try {
    userInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
  } catch (e) {
    // 忽略解析错误
  }
  
  // 检查持久化的用户ID
  const userId = localStorage.getItem('vben-user-id');
  
  authLog('Current auth status:', {
    hasToken: !!token,
    tokenLength: token?.length || 0,
    hasUserInfo: !!userInfo,
    hasUserId: !!userId,
    userId: userId,
    userInfoKeys: userInfo ? Object.keys(userInfo) : [],
    currentPath: window.location.pathname,
    timestamp: new Date().toISOString()
  });
  
  return {
    hasToken: !!token,
    hasUserInfo: !!userInfo,
    hasUserId: !!userId,
    token,
    userInfo,
    userId,
    path: window.location.pathname
  };
}

/**
 * 监控路由守卫行为
 */
export function monitorRouteGuard() {
  if (!AUTH_DEBUG) return;
  
  authLog('Route guard monitoring enabled');
  
  // 监控路由变化
  window.addEventListener('beforeunload', () => {
    authLog('Page is about to refresh/unload');
  });
} 
 